extends CharacterBody2D
signal shoot(bullet_scene, direction)

@export var player_speed : float = 100
@export var animator : AnimatedSprite2D
var is_game_over :bool = false
@export var bullet_scene : PackedScene
var Bullet = preload("res://Scene/bullet.tscn")


func _process(delta: float) -> void:
	if velocity == Vector2.ZERO or is_game_over:
		$running.stop()
	elif not $running.playing:
		$running.play()

func _physics_process(delta: float) -> void:
	if not is_game_over:
		velocity = Input.get_vector("left","right","up","down")*player_speed
		move_and_slide()
		if velocity == Vector2.ZERO:
			animator.play("idle")
		else :
			animator.play("run")
			
	

func game_over():
	if not is_game_over:
		is_game_over = true
		animator.play("game over")
		get_tree().current_scene.show_game_over()
		$gameover.play()
		$restart.start()


func _input(event : InputEvent) :
	if not is_game_over  :
		if event is InputEventMouseButton and event.pressed:
			if event.button_index == MOUSE_BUTTON_LEFT:
				var mouse_pos = get_global_mouse_position()
				var direction = (mouse_pos - global_position).normalized()
				emit_signal("shoot", Bullet, direction)



func _reload_scene() -> void:
	get_tree().reload_current_scene()


func _on_shoot(bullet_scene: Variant, direction: Variant) -> void:
	var bullet = bullet_scene.instantiate()
	bullet.global_position = $".".global_position + Vector2(6,6)
	bullet.velocity = direction
	bullet.rotation = direction.angle()
	add_child(bullet)
